import 'dart:convert';
import 'dart:typed_data';

import 'package:common_utils/common_utils.dart';
import 'package:date_format/date_format.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:image_picker/image_picker.dart';
import 'package:pax_info_app/db/provider/clock/clock_db_provider.dart';
import 'package:pax_info_app/model/clock.dart';
import 'package:pax_info_app/provider/view_state_model.dart';
import 'package:pax_info_app/repository/app_repository.dart';
import 'package:pax_info_app/utils/common_utils.dart';

class ClockListModel extends ViewStateModel {

  // final int userNo;
  ClockListModel();

  Clock? _clock;
  Clock? get clock => _clock;

  List<Clock>? _list;
  List<Clock>? get list => _list;

  late List _periodList;
  List get periodList => _periodList;

  double _totalSalaryDays = 0;
  double get totalSalaryDays => _totalSalaryDays;

  double _totalLateDays = 0;
  double get totalLateDays => _totalLateDays;

  double _totalLeaveEarlyDays = 0;
  double get totalLeaveEarlyDays => _totalLeaveEarlyDays;

  ClockDbProvider clockDbProvider = new ClockDbProvider();

  initData({String? fDate}) async {
    setBusy();
    try {
      String _date = formatDate(DateTime.now(), [yyyy, '-', mm]);
      print('>>>>>> fDate: $fDate');
      _list = await clockDbProvider.getData(fDate: fDate??_date);
      print('>>>>>> _list: ${_list?.length}');
      if (_list != null) {
        _totalSalaryDays = 0;
        _totalLateDays = 0;
        _totalLeaveEarlyDays = 0;
        _list!.forEach((element) {
          _totalSalaryDays = NumUtil.add(_totalSalaryDays, element.salaryDays??0);
          _totalLateDays = NumUtil.add(_totalLateDays, element.lateDays??0);
          _totalLeaveEarlyDays += NumUtil.add(_totalLeaveEarlyDays, element.leaveEarlyDays??0);
        });

        String _date = formatDate(DateTime.now(), [yyyy, '-', mm, '-', dd]);
        _clock = await getDetail(_date);
        setIdle();
        return true;
      } else {
        setEmpty();
        return false;
      }
    } catch (e, s) {
      setError(e,s);
      return false;
    }
  }

  Future<Clock?> getDetail(String fDate) async {
    Clock? c = await clockDbProvider.getDetail(fDate);
    _clock = c;
    notifyListeners();
    return c;
  }

}